package com.anosine.gpsl.android.ui.fragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.anosine.gpsl.android.GPSLApp;
import com.anosine.gpsl.android.R;
import com.anosine.gpsl.android.base.BaseFragment;
import com.anosine.gpsl.android.entity.Login;
import com.anosine.gpsl.android.entity.PushMessageBean;
import com.anosine.gpsl.android.ui.FortifiedView;
import com.anosine.gpsl.android.util.BundleKey;
import com.anosine.gpsl.android.util.ToastHelper;
import com.anosine.gpsl.android.util.UserInfoProxy;
import com.anosine.gpsl.android.util.ormdb.DaoHelper;
import com.anosine.gpsl.android.widget.pulltorefresh.PullToRefreshBase;
import com.anosine.gpsl.android.widget.pulltorefresh.PullToRefreshListView;

/**
 * @Title: TabMessageFragment
 * @Package com.anosine.gpsl.android.ui.fragment
 * @Description: 报警消息界面
 * @author: sunny
 * @date: 2015-11-23
 * @version V1.0
 */

public class TabMessageFragment extends BaseFragment implements
		PullToRefreshBase.OnRefreshListener2, View.OnClickListener {
	private List<PushMessageBean> mListBeanInfo = new ArrayList<PushMessageBean>();
	List<PushMessageBean> mListBeanInfoSort = new ArrayList<PushMessageBean>();

	private PullToRefreshListView mPRLVshow;
	private ListView mLVShow;
	private ShowMessageListAdapter mDataAdapter;
	private DaoHelper<PushMessageBean> pushMessageDao;
	PushMessageBean pushMessageBean;
	private LinearLayout after_ClickManager;
	private TextView del;
	private CheckBox selectAll;
	private boolean isClickManger = false;
	private Map<Integer, Boolean> isCheckedMap;
	private ImageView btn_common_back;

	/**
	 * 方法名：onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
	 * savedInstanceState) 功 能：创建该Fragment的视图 参 数：LayoutInflater inflater
	 * LayoutInflater是用来找res/layout/下的xml布局文件，并且实例化 ViewGroup container
	 * ViewGroup是Layout的基类, Bundle savedInstanceState 返回值： View view
	 */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_main_tab_message,
				container, false);
		view.findViewById(R.id.btn_msg_manager).setOnClickListener(this);
		after_ClickManager = (LinearLayout) view
				.findViewById(R.id.after_ClickManager);
		btn_common_back = (ImageView) view.findViewById(R.id.btn_common_back);
		btn_common_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (isClickManger) {
					after_ClickManager.setVisibility(View.GONE);
					isClickManger = false;
					mDataAdapter.notifyDataSetChanged();
					btn_common_back.setVisibility(View.GONE);

				} else {
					after_ClickManager.setVisibility(View.VISIBLE);
					isClickManger = true;
					mDataAdapter.notifyDataSetChanged();
					btn_common_back.setVisibility(View.VISIBLE);

				}
			}
		});
		selectAll = (CheckBox) view.findViewById(R.id.selectAll);
		selectAll
				.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						Set<Integer> set = isCheckedMap.keySet();
						Iterator<Integer> iterator = set.iterator();
						if (isChecked) {
							while (iterator.hasNext()) {
								Integer keyId = iterator.next();
								isCheckedMap.put(keyId, true);
								selectAll.setText("取消全选");
							}
						} else {
							while (iterator.hasNext()) {
								Integer keyId = iterator.next();
								isCheckedMap.put(keyId, false);
								selectAll.setText("全选");
							}
						}
						mDataAdapter.notifyDataSetChanged();
					}
				});
		if (TabMonitoringFragmentNew.isPlayer == 0) {
		} else if (TabMonitoringFragmentNew.isPlayer == 1) {
			TabMonitoringFragmentNew.player.stop();
		}
		del = (TextView) view.findViewById(R.id.del);
		del.setOnClickListener(this);
		isCheckedMap = new HashMap<Integer, Boolean>();
		if (pushMessageDao == null) {
			pushMessageDao = new DaoHelper<PushMessageBean>(
					GPSLApp.getInstance(), PushMessageBean.class);
		}
		mPRLVshow = (PullToRefreshListView) view
				.findViewById(R.id.plv_common_pulltofresh);
		mPRLVshow.setOnRefreshListener(this);
		mPRLVshow.setEmptyView(inflater.inflate(R.layout.common_empty_show,
				null));
		mLVShow = mPRLVshow.getRefreshableView();
		showData();
		userInfo = UserInfoProxy.getInstance().getLoginInfo();
		return view;
	}
	Login userInfo;
	public Handler mHandlerRefresh = new Handler() {
		// 匿名内部类
		// 重写的handleMessage
		@Override
		public void handleMessage(Message msg) {
			// 根据收到的消息的what类型处理
			super.handleMessage(msg);
			if (mDataAdapter == null) {
				mDataAdapter = new ShowMessageListAdapter();
				mLVShow.setAdapter(mDataAdapter);
			}
			mDataAdapter.notifyDataSetChanged();
		}
	};

	/**
	 * 方法名：showData() 功能：显示数据 参数：无 返回值：无
	 * */
	public void showData() {
		new Thread(mRunable).start();
	}

	private Runnable mRunable = new Runnable() {

		@Override
		public void run() {
			try {
				if (mListBeanInfoSort != null) {
					mListBeanInfoSort.clear();
				}
				DaoHelper<PushMessageBean> rowImageDao = new DaoHelper<PushMessageBean>(
						getActivity(), PushMessageBean.class);
				//mListBeanInfo = rowImageDao.queryForAll();
				mListBeanInfo=rowImageDao.queryForEq("hid", userInfo.holdid);

				for (int i = 0; i < mListBeanInfo.size(); i++) {
					mListBeanInfoSort.add(mListBeanInfo.get(mListBeanInfo
							.size() - (i + 1)));
				}
				// 初始化数据
				for (int i = 0; i < mListBeanInfoSort.size(); i++) {
					isCheckedMap.put(i, false);
				}
				Message msg = new Message();
				mHandlerRefresh.sendMessage(msg);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	/**
	 * 方法名：stopLoadingRefreshState() 功能：停止更新 参数：无 返回值：无
	 * */
	private void stopLoadingRefreshState() {
		if (mPRLVshow != null) {
			mPRLVshow.postDelayed(new Runnable() {
				@Override
				public void run() {
					mPRLVshow.onRefreshComplete();
				}
			}, 100);
		}
	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase refreshView) {
		stopLoadingRefreshState();
	}

	@Override
	public void onPullUpToRefresh(PullToRefreshBase refreshView) {
		stopLoadingRefreshState();
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.btn_msg_manager:
			// showData();
			// mListBeanInfoSort.clear();w
			// mPRLVshow.setRefreshing();w

			if (mListBeanInfo == null) {
				ToastHelper.toast("现在没有数据，无需管理！");
			} else {
				if (isClickManger) {
					after_ClickManager.setVisibility(View.GONE);
					isClickManger = false;
					mDataAdapter.notifyDataSetChanged();
					btn_common_back.setVisibility(View.GONE);
				} else {
					after_ClickManager.setVisibility(View.VISIBLE);
					isClickManger = true;
					mDataAdapter.notifyDataSetChanged();
					btn_common_back.setVisibility(View.VISIBLE);
				}
			}
			break;
		case R.id.del:
			boolean isHaveDel = false;
			for (int i = 0; i < mListBeanInfoSort.size(); i++) {
				if (isCheckedMap.get(i)) {
					isHaveDel = true;
					pushMessageDao.delete(mListBeanInfoSort.get(i));
				}
			}
			if (isHaveDel) {
				ToastHelper.toast("删除成功！");

				DaoHelper<PushMessageBean> rowImageDao = new DaoHelper<PushMessageBean>(
						getActivity(), PushMessageBean.class);
				//mListBeanInfo = rowImageDao.queryForAll();
				mListBeanInfo=rowImageDao.queryForEq("hid", userInfo.holdid);

				if (mListBeanInfo.size() == 0) {
					after_ClickManager.setVisibility(View.GONE);
					btn_common_back.setVisibility(View.GONE);
					isClickManger = false;
				}
				showData();
			}
			break;
		}
	}

	class ShowMessageListAdapter extends BaseAdapter implements
			View.OnClickListener {
		ViewHolder holder = null;

		public ShowMessageListAdapter() {
		}

		@Override
		public int getCount() {
			return mListBeanInfoSort != null ? mListBeanInfoSort.size() : 0;
		}

		@Override
		public PushMessageBean getItem(int i) {
			return mListBeanInfoSort.get(i);
		}

		@Override
		public long getItemId(int i) {
			return i;
		}

		@SuppressLint("ResourceAsColor")
		@Override
		public View getView(final int i, View view, ViewGroup viewGroup) {

			if (view == null) {
				view = LayoutInflater.from(getActivity()).inflate(
						R.layout.fragment_main_tab_message_item, null);
				holder = new ViewHolder();
				holder.mArea = view.findViewById(R.id.area_message_item_info);
				holder.tvInfo = (TextView) view
						.findViewById(R.id.tv_message_item_info);
				holder.tvHn=(TextView)view.findViewById(R.id.tv_message_item_hn);
				holder.tvTitle = (TextView) view
						.findViewById(R.id.tv_message_item_title);
				holder.tvDate = (TextView) view
						.findViewById(R.id.tv_message_item_date);
				holder.all_check_btn = (CheckBox) view
						.findViewById(R.id.all_check_btn);
				view.setTag(holder);
			} else {
				holder = (ViewHolder) view.getTag();
			}

			PushMessageBean info = getItem(i);
			if (isClickManger) {
			} else {
				holder.mArea.setTag(info);
			}
			holder.all_check_btn.setChecked(isCheckedMap.get(i));
			if (isClickManger) {
				holder.all_check_btn.setVisibility(View.VISIBLE);
				holder.tvDate.setVisibility(View.GONE);
			} else {
				holder.all_check_btn.setVisibility(View.GONE);
				holder.tvDate.setVisibility(View.VISIBLE);
			}
			holder.all_check_btn
					.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
						@Override
						public void onCheckedChanged(CompoundButton buttonView,
								boolean isChecked) {
							if (isChecked) {
								isCheckedMap.put(i, true);
							} else {
								isCheckedMap.put(i, false);
							}
						}
					});
			holder.mArea.setOnClickListener(this);
			if (info.getDesc() != null) {
				if (info.getDesc().contains("$url$")) {
					final String[] getUrl = info.getDesc().split("\\$url\\$");
					String content = "";
					for (int j = 0; j < getUrl.length - 1; j++) {
						content = content + getUrl[j];
					}
					holder.tvInfo.setText(content);
				} else {
					holder.tvInfo.setText(info.getDesc());
				}
			}
			if (info.getTitle().indexOf("报警") != -1) {
				// 包含 标题红色显示
				holder.tvTitle.setTextColor(Color.rgb(255, 0, 0));
			}
			holder.tvHn.setText(info.getHn());
			holder.tvTitle.setText(info.getTitle());

			// 获取当前时间
			SimpleDateFormat sdfAllShow = new SimpleDateFormat("yyyy-MM-dd");
			if (info.getDate().substring(0, 10)
					.equals(sdfAllShow.format(new Date()))) {
				holder.tvDate.setText(info.getDate().substring(11, 19));
			} else {
				holder.tvDate.setText(info.getDate().substring(0, 10));
			}
			return view;
		}

		/**
		 * 方法名：onClick(View view) 功能：处理点击事件 参数：View view 被点击的view 返回值：无
		 */
		@Override
		public void onClick(View view) {
			switch (view.getId()) {
			case R.id.area_message_item_info: {
				if (isClickManger) {
					// String position = (String) view.getTag();
					// isCheckedMap.put(Integer.parseInt(position),true);
					// 编辑模式下

				} else {
					PushMessageBean info = (PushMessageBean) view.getTag();
					pushMessageBean = info;
					if (info != null) {
						// 跳转到信息详情页面

						Bundle args = new Bundle();
						args.putSerializable(BundleKey.TAG_SCENERY_DATA, info);
						Fragment newFragment = new ShowReceivePushFragment();
						FragmentTransaction transaction = getFragmentManager()
								.beginTransaction();
						newFragment.setArguments(args);
						transaction
								.add(R.id.area_show_content, newFragment, "");
						transaction.addToBackStack(null);
						transaction.commit();

					}
				}
			}
				break;
			}
		}

		/**
		 * @ClassName: ViewHolder
		 * @Description: 自己的ViewHolder
		 * @author: Sunny
		 * @date: 2015.10.30
		 * 
		 */
		class ViewHolder {
			View mArea;
			TextView tvTitle;
			TextView tvInfo;
			TextView tvDate;
			TextView tvHn;
			CheckBox all_check_btn;
		}
	}

}
